package com.phpxiu.app.view;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import com.phpxiu.app.config.Constants;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.controller.avcontroller.QavsdkControl;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.LoginModeContent;
import com.phpxiu.app.model.MySelfInfo;
import com.phpxiu.app.model.response.LoginMode;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.OKHttpResponseModel;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.push.MessageEvent;
import com.phpxiu.app.push.PushUtil;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.custom.MEditText;
import com.phpxiu.app.view.custom.WindowLayout;
import com.tencent.TIMCallBack;
import com.tencent.TIMManager;
import com.tencent.TIMOfflinePushSettings;
import com.tencent.TIMUser;
import com.tencent.av.sdk.AVError;
import com.tencent.bugly.imsdk.crashreport.CrashReport;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 重置密码界面
 * Created by 吴金洲 on 2016/8/30
 */
final public class UIResetPwd extends UIBase implements View.OnClickListener,TIMCallBack {
    public final static String TAG = "UIResetPwd";
    private final static int COUNT_DOWN_HANDLE = 0x1;
    private final static int COUNT_DOWN_HANDLE_STATE = 0x2;
    public final static int REQUEST_PICK_COUNTRY_CODE=0x3;
    private WindowLayout mainView;
    private TextView regionsView;//区域名称
    private TextView countryCodeView;//区号
    private MEditText accountInput;
    private MEditText codeInput;
    private Button requestCodeBtn;
    private MEditText pwdInput;
    private ImageButton cleanAccount, cleanPwd;

    private Button submitBtn;
    private boolean isRequesting = false;//正在请求重置

    private int maxTime = 60;
    private boolean isCountDownEnd = true;//倒计时结束
    private Timer timer;
    private TimerTask task;
    private OKHttpParam checkParam;

    private String countryCode="";//国际电话区号

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ui_reset_pwd);
        init();
    }

    final private void init() {
        mainView = (WindowLayout) findViewById(R.id.reset_pwd_root_view);
        mainView.setOnClickListener(this);
        findViewById(R.id.top_bar_back_btn).setOnClickListener(this);
        findViewById(R.id.pick_country_link).setOnClickListener(this);
        regionsView=(TextView)findViewById(R.id.country_name);
        regionsView.setText(getString(R.string.default_country_name));
        countryCodeView=(TextView)findViewById(R.id.country_code);
        countryCode=getString(R.string.default_region_code);
        countryCodeView.setText("+"+countryCode);
        accountInput = (MEditText) findViewById(R.id.reset_pwd_account_input);
        accountInput.addTextChangedListener(new InputTextWatcher(R.id.reset_pwd_account_input));
        cleanAccount = (ImageButton) findViewById(R.id.phone_number_input_clean_btn);
        cleanAccount.setOnClickListener(this);
        codeInput = (MEditText) findViewById(R.id.code_input);
        codeInput.addTextChangedListener(new InputTextWatcher(R.id.code_input));
        requestCodeBtn = (Button) findViewById(R.id.reset_pwd_request_code_btn);
        requestCodeBtn.setEnabled(false);
        requestCodeBtn.setOnClickListener(this);
        pwdInput = (MEditText) findViewById(R.id.reset_pwd_input);
        pwdInput.addTextChangedListener(new InputTextWatcher(R.id.reset_pwd_input));
        cleanPwd = (ImageButton) findViewById(R.id.password_input_clean_btn);
        cleanPwd.setOnClickListener(this);
        submitBtn = (Button) findViewById(R.id.reset_btn);
        submitBtn.setOnClickListener(this);
        countDown();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.top_bar_back_btn:
                onBackPressed();
                break;
            case R.id.pick_country_link:
                pickCountryCode();
                break;
            case R.id.phone_number_input_clean_btn:
                accountInput.setText("");
                break;
            case R.id.password_input_clean_btn:
                pwdInput.setText("");
                break;
            case R.id.reset_pwd_request_code_btn:
                requestCode();
                break;
            case R.id.reset_btn:
                resetPwd();
            case R.id.reset_pwd_root_view:
                hideSoftBoard();
                break;
            default:
                break;
        }
    }

    /**
     * 点击发送，请求验证码
     */
    final private void requestCode() {
        maxTime = 60;
        if (checkParam == null) {
            checkParam = OKHttpParam.builder();
        }
        checkParam.put("phone", accountInput.getText().toString());
        checkParam.put("type", "login");
        checkParam.put("code",countryCode);
        requestCodeBtn.setEnabled(false);
        OKHttp.post(HttpConfig.API_CHECK_PHONE, checkParam.jsonParam(), TAG, new OKHttpUIHandler(OKHttpResponseModel.class) {
            @Override
            public void onSuccess(Object model) {
                OKHttpResponseModel m = (OKHttpResponseModel) model;
                KKYUtil.log("验证手机结果：" + m.getResponseStr());
                handler.sendEmptyMessage(COUNT_DOWN_HANDLE_STATE);
            }

            @Override
            public void onErr(String errMsg) {
                mainView.showTopMsg(errMsg);
                requestCodeBtn.setEnabled(true);
            }
        });
    }

    /**
     * 倒计时
     */
    final private void countDown() {
        if (timer == null) {
            timer = new Timer(true);
        }
        if (task == null) {
            task = new TimerTask() {
                @Override
                public void run() {
                    handler.sendEmptyMessage(COUNT_DOWN_HANDLE);
                }
            };
        }
        timer.schedule(task, 0, 1000);
    }

    @Override
    public void handleMsg(Message msg) {
        switch (msg.what) {
            case COUNT_DOWN_HANDLE:
                if (maxTime > 0) {
                    if (!isCountDownEnd) {
                        maxTime--;
                        requestCodeBtn.setText(maxTime + "");
                    }
                } else {
                    handler.removeCallbacksAndMessages(null);
                    maxTime = 60;
                    requestCodeBtn.setText(getString(R.string.ui_register_request_code_title));
                    if(TextUtils.getTrimmedLength(accountInput.getText())>5){
                        if(!requestCodeBtn.isEnabled()){
                            requestCodeBtn.setEnabled(true);
                        }
                    }else{
                        if(requestCodeBtn.isEnabled()){
                            requestCodeBtn.setEnabled(false);
                        }
                    }
                    isCountDownEnd = true;
                }
                break;
            case COUNT_DOWN_HANDLE_STATE:
                isCountDownEnd = false;
                break;
            default:
                break;
        }
    }

    /**
     * 选择国际区号
     */
    final private void pickCountryCode(){
        Intent pick=new Intent(this,UICountryCodePicker.class);
        startActivityForResult(pick,REQUEST_PICK_COUNTRY_CODE);
    }

    /**
     * 确定重置
     */
    final private void resetPwd() {
        if (isRequesting) {
            return;
        }

        if(TextUtils.isEmpty(accountInput.getText())||!TextUtils.isDigitsOnly(accountInput.getText())
                ||TextUtils.getTrimmedLength(accountInput.getText())<6){
            //mainView.showTopMsg(getString(R.string.ui_register_invalid_account));
            return;
        }

        if (TextUtils.isEmpty(codeInput.getText())) {
            //mainView.showTopMsg(getString(R.string.ui_register_empty_code));
            return;
        }

        if (TextUtils.isEmpty(pwdInput.getText())) {
            //mainView.showTopMsg(getString(R.string.ui_register_empty_password));
            return;
        }
        if (TextUtils.getTrimmedLength(pwdInput.getText()) < 6) {
            //mainView.showTopMsg(getString(R.string.ui_register_pwd_length_err));
            return;
        }
        isRequesting = true;
        final String phone = accountInput.getText().toString().trim();
        final String pwd = pwdInput.getText().toString().trim();
        final String code = codeInput.getText().toString().trim();
        OKHttpParam param = OKHttpParam.builder();
        param.put("phone", countryCode+phone);
        param.put("code", code);
        param.put("password", pwd);
        OKHttp.post(HttpConfig.API_RESET_PASSWORD, param.jsonParam(), TAG, new OKHttpUIHandler(LoginMode.class) {
            @Override
            public void onSuccess(Object model) {
                LoginMode m = (LoginMode) model;
                KKYUtil.log("密码重置结果:" + m.getResponseStr());
                if (m.getData() != null) {
                    loginSuccess(m.getData());
                } else {
                    //mainView.showTopMsg(getString(R.string.login_failed_or_err));
                }
                isRequesting = false;
            }

            @Override
            public void onErr(String errMsg) {
                mainView.showTopMsg(errMsg);
                isRequesting = false;
            }
        });
    }


    /**
     * 登录成功结果
     *
     * @param result
     */
    private void loginSuccess(LoginModeContent result) {
        KKYUtil.log("上传签名：" + result.getCossig());
        MySelfInfo.getInstance().setId(result.getUserinfo().getUid());
        MySelfInfo.getInstance().setUserSig(result.getSig());
        MySelfInfo.getInstance().setNickName(result.getUserinfo().getNickname());
        MySelfInfo.getInstance().setAvatar(result.getUserinfo().getAvatar());
        MySelfInfo.getInstance().setSign(result.getUserinfo().getIntro());
        MySelfInfo.getInstance().setCosSig(result.getCossig());
        try {
            int roomNum = Integer.parseInt(result.getUserinfo().getRoomid());
            MySelfInfo.getInstance().setMyRoomNum(roomNum);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        MySelfInfo.getInstance().setMobilenum(result.getUserinfo().getMobilenum());
        MySelfInfo.getInstance().setSex(result.getUserinfo().getSex());
        MySelfInfo.getInstance().setAddress(result.getUserinfo().getAddress());
        MySelfInfo.getInstance().setVerifyState(result.getUserinfo().getApproved());
        try {
            MySelfInfo.getInstance().setMoney(Long.parseLong(result.getUserinfo().getMoney()));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        try {
            MySelfInfo.getInstance().setLvl(Integer.parseInt(result.getUserinfo().getLvl()));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        MySelfInfo.getInstance().setMerrage(result.getUserinfo().getMerrage());
        try {
            MySelfInfo.getInstance().setAge(Integer.parseInt(result.getUserinfo().getAge()));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        MySelfInfo.getInstance().writeToCache(this);
        IMLogin(MySelfInfo.getInstance().getId(), MySelfInfo.getInstance().getUserSig());
    }

    /**
     * 登录IM
     *
     * @param identify         用户id
     * @param userSig//登录获取的签名
     */
    private void IMLogin(String identify, String userSig) {
        TIMUser user = new TIMUser();
        user.setAccountType(String.valueOf(Constants.ACCOUNT_TYPE));
        user.setAppIdAt3rd(String.valueOf(Constants.SDK_APPID));
        user.setIdentifier(identify);
        //发起登录请求
        TIMManager.getInstance().login(Constants.SDK_APPID, user, userSig, UIResetPwd.this);
    }

    /**
     * IM 登录失败
     *
     * @param i
     * @param s
     */
    @Override
    public void onError(int i, String s) {
        if (i == 6012) {
            mainView.showTopMsg(getString(R.string.login_failed));
        }
        //发送日志到错误统计
        CrashReport.postCatchedException(new Throwable("Main IM Login failed：" + i + "-->" + s));
        if(KKYUtil.DEBUG){
            mainView.showTopMsg(i + "-->" + s);
        }
    }

    /**
     * IM登录成功
     */
    @Override
    public void onSuccess() {
        TIMOfflinePushSettings SETTINGS = new TIMOfflinePushSettings();
        SETTINGS.setEnabled(true);
        TIMManager.getInstance().configOfflinePushSettings(SETTINGS);
        //初始化程序后台后消息推送
        PushUtil.getInstance();
        //初始化消息监听
        MessageEvent.getInstance();
        if (startAVSDK()) {
            Intent main = new Intent(UIResetPwd.this, Main.class);
            startActivity(main);
            setResult(RESULT_OK);
            finish();
        } else {
            mainView.showTopMsg(getString(R.string.login_failed));
            CrashReport.postCatchedException(new Exception("登录失败,AV SDK初始化失败"));
        }
    }

    /**
     * 初始化音视频SDK
     */
    public static boolean startAVSDK() {
        QavsdkControl.getInstance().setAvConfig(Constants.SDK_APPID, "" + Constants.ACCOUNT_TYPE, MySelfInfo.getInstance().getId(), MySelfInfo.getInstance().getUserSig());
        int startResult=QavsdkControl.getInstance().startContext();
        if(startResult!=AVError.AV_OK){
            return false;
        }
        return true;
    }

    /**
     * 隐藏输入软盘
     */
    final private void hideSoftBoard() {
        View view = getCurrentFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==REQUEST_PICK_COUNTRY_CODE){//选择国际区号结果
            if(resultCode==RESULT_OK){
                countryCode=data.getStringExtra(UICountryCodePicker.SELECTED_CODE);
                String regionName=data.getStringExtra(UICountryCodePicker.SELECTED_COUNTRY);
                regionsView.setText(regionName);
                countryCodeView.setText("+"+countryCode);
            }
        }
    }

    @Override
    protected void onDestroy() {
        //停止计时器及任务，并销毁
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (task != null) {
            task.cancel();
            task = null;
        }
        handler.removeCallbacksAndMessages(null);
        handler = null;
        super.onDestroy();
    }

    /**
     * 检测是否可以点击提交表单
     */
    public void checkCanSubmit(){
        boolean accountValid=!TextUtils.isEmpty(accountInput.getText())&&TextUtils.getTrimmedLength(accountInput.getText())>5;
        boolean codeValid=!TextUtils.isEmpty(codeInput.getText())&&TextUtils.getTrimmedLength(codeInput.getText())>3;
        boolean pwdValid=TextUtils.getTrimmedLength(pwdInput.getText())>=6;
        if(accountValid&&codeValid&&pwdValid){
            if(!submitBtn.isEnabled()){
                submitBtn.setEnabled(true);
            }
        }else{
            if(submitBtn.isEnabled()){
                submitBtn.setEnabled(false);
            }
        }
    }


    /**
     * 输入框监听
     */
    class InputTextWatcher implements TextWatcher{
        private int viewId;

        InputTextWatcher(int viewId) {
            this.viewId = viewId;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            switch (viewId){
                case R.id.reset_pwd_account_input:
                    if(TextUtils.isEmpty(s)){
                        if(cleanAccount.getVisibility()==View.VISIBLE){
                            cleanAccount.setVisibility(View.INVISIBLE);
                        }
                    }else{
                        if(cleanAccount.getVisibility()!=View.VISIBLE){
                            cleanAccount.setVisibility(View.VISIBLE);
                        }
                    }
                    if(isCountDownEnd){
                        if(TextUtils.getTrimmedLength(s)>5){
                            if(!requestCodeBtn.isEnabled()){
                                requestCodeBtn.setEnabled(true);
                            }
                        }else{
                            if(requestCodeBtn.isEnabled()){
                                requestCodeBtn.setEnabled(false);
                            }
                        }
                    }
                    break;
                case R.id.reset_pwd_input:
                    if(TextUtils.isEmpty(s)){
                        if(cleanPwd.getVisibility()==View.VISIBLE){
                            cleanPwd.setVisibility(View.INVISIBLE);
                        }
                    }else{
                        if(cleanPwd.getVisibility()!=View.VISIBLE){
                            cleanPwd.setVisibility(View.VISIBLE);
                        }
                    }
                    break;
            }
            checkCanSubmit();
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }
}
